package com.dsh.service;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class SearchService {
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Value("${guli.elasticsearch.index}")
    String index;


    public Map search(Integer page, Integer size, Map map) throws IOException {
       Map map1=new HashMap();

        SearchRequest searchRequest = new SearchRequest(index);

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        searchSourceBuilder.from((page-1)*size);
        searchSourceBuilder.size(size);

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        String name = (String) map.get("name");
        if (!StringUtils.isEmpty(name)){
            MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", name);
            boolQueryBuilder.must(matchQueryBuilder);
        }
        searchSourceBuilder.query(boolQueryBuilder);

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<strong style='color:red'>");
        highlightBuilder.postTags("</strong>");
        highlightBuilder.field("name");
        searchSourceBuilder.highlighter(highlightBuilder);

        TermsAggregationBuilder catalog_name = AggregationBuilders.terms("1911A_catalog").field("catalog_name");
        searchSourceBuilder.aggregation(catalog_name);


        searchRequest.source(searchSourceBuilder);
        restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);


        return map1;
    }
}
